<template>
  <el-upload
    class="avatar-uploader"
    :http-request="handleUpload"
    :show-file-list="false"
    :before-upload="beforeAvatarUpload"
  >
    <img
      v-if="imageUrl || changeImg"
      :src="imageUrl || changeImg"
      class="avatar"
    />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
</template>

<script>
import Cloud from "leancloud-storage";
function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener("load", () => callback(reader.result));
  reader.readAsDataURL(img);
}
export default {
  props: {
    //接收当前组件v-model传入的数据
    changeImg: {
      type: String,
    },
  },
  data() {
    return {
      imageUrl: "",
    };
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    //自定义上传函数
    handleUpload(info) {
      console.log(info);
      // 将本地文件资源对象，转换为base64的编码
      getBase64(info.file, (base64) => {
        console.log(base64);
        const data = { base64 };
        const file = new Cloud.File("vue-admin-2301.png", data); //将base64的编码，构建为LeanCloud资源对象
        //上传图片并获取后端下发的图片链接
        file.save().then((res) => {
          console.log(res);
          let { url } = res.attributes; //解构赋值
          // let url = res.attributes.url
          this.imageUrl = url; //展示预览图
          this.$emit("update:changeImg", url);
        });
      });
    },

    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
  },
};
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
